package com.bjc.chapter16.reference;

import java.lang.ref.SoftReference;

/**
 * @program: jvm_demo
 * @description: 软引用
 * @author: bjc
 * @create: 2022-02-17 21:58
 */
public class SoftReferenceTest {

    public static class User {
        public int id;
        public String name;

        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        //创建对象，建立软引用
        SoftReference<User> userSoftRef = new SoftReference<>(new User(1, "tom"));
        //从软引用中重新获得强引用对象
        System.out.println(userSoftRef.get());

        System.gc();
        System.out.println("After GC");
        //垃圾回收之后获得软引用中的对象
        System.out.println(userSoftRef.get()); //由于对空间内存足够，所以不会回收软引用的可达对象

        try {
            //让系统认为内存资源紧张、不够
//            byte[] b = new byte[1024 * 1024 * 7];
            byte[] b = new byte[1024 * 7168 -695*1024];
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            //再次从软引用中获取数据
            System.out.println(userSoftRef.get()); //在报OOM之前，垃圾回收器会回收软引用的可达对象
        }
    }
}
